﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using deviceManage.Models;
using deviceManage.vo;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using deviceManage.Filters;
using deviceManage.Tools;
using deviceManage.VO;

namespace deviceManage.Controllers
{
    /// <summary>
    /// 设备外借控制器
    /// </summary>
    [CheckLoginAttribute]
    public class DeviceLendController : Controller
    {
        private readonly DeviceCtx _context;

        public DeviceLendController(DeviceCtx context)
        {
            _context = context;
        }

        public IActionResult Index()
        {
            //获取设备分类，用于下拉显示
            var typeList = _context.DeviceType.Where(p => p.Deleted == 0).OrderBy(p => p.SortOrder).ToList();
            //是否只读权限
            int? flag = HttpContext.Session.GetInt32("viewFlag");
            return View(Tuple.Create(typeList,flag));
        }


        

       

        /// <summary>
        /// 获取所有设备外借记录，ajax
        /// </summary>
        /// <param name="id">设备id</param>
        /// <returns></returns>
        public AjaxResult LendLog(int page, int limit,string name)
        {
            AjaxResult r = new AjaxResult();
            IQueryable<LendLog> query = _context.LendLog;

            if (!string.IsNullOrWhiteSpace(name))
            {
                query = query.Where(p => p.Device.Name.Contains(name));
            }

            if (!string.IsNullOrWhiteSpace(Request.Form["deviceTypeId"]))
            {
                string typeId = Request.Form["deviceTypeId"];
                query = query.Where(p => p.Device.DeviceTypeId == typeId);
            }

            if (!string.IsNullOrWhiteSpace(Request.Form["deviceId"]))
            {
                string deviceId = Request.Form["deviceId"];
                query = query.Where(p => p.Device.DeviceId == deviceId);
            }
            if (!string.IsNullOrWhiteSpace(Request.Form["start"]))
            {
                DateTime start = DateTime.Parse(Request.Form["start"]);
                query = query.Where(p => p.LendDate >= start);
            }
            if (!string.IsNullOrWhiteSpace(Request.Form["end"]))
            {
                DateTime end = DateTime.Parse(Request.Form["end"]);
                query = query.Where(p => p.LendDate <= end);
            }
            if (!string.IsNullOrWhiteSpace(Request.Form["returnStart"]))
            {
                DateTime start = DateTime.Parse(Request.Form["returnStart"]);
                query = query.Where(p => p.ReturnDate >= start);
            }
            if (!string.IsNullOrWhiteSpace(Request.Form["returnEnd"]))
            {
                DateTime end = DateTime.Parse(Request.Form["returnEnd"]);
                query = query.Where(p => p.ReturnDate <= end);
            }


            r.Count = query.Include(p => p.Device).Count();
            r.Code = 0;
            try
            {
                r.Data = query.Include(p=>p.Device).ThenInclude(p=>p.DeviceType).OrderByDescending(p => p.LendDate)
                    .Skip((page - 1) * limit).Take(limit)
                    .ToList();
            }
            catch (Exception e)
            {
                r.Msg = e.Message;
            }
            return r;
        }

        /// <summary>
        /// 进入添加外借记录页面
        /// </summary>
        /// <returns></returns>
        public IActionResult GoAddLendLog()
        {
            List<Device> list = _context.Device.Where(p => p.Deleted == 0 && p.Status == DeviceState.STATE_NORMAL).OrderBy(p => p.Name).ToList();
            var departList = _context.Depart.Where(p => p.Deleted == 0).OrderBy(p => p.SortOrder).ToList();
            return View(Tuple.Create(list,departList));
        }

        /// <summary>
        /// 添加外借记录
        /// </summary>
        /// <param name="log"></param>
        /// <returns></returns>
        public AjaxResult AddLendLog(LendLog log)
        {    
            log.State = 1;
            _context.LendLog.Add(log);
            _context.SaveChanges();

            //更新设备状态
            var device = _context.Device.Single(p => p.Id == log.DeviceId);
            device.Status = DeviceState.STATE_LEND;
            _context.Device.Update(device);
            _context.SaveChanges();

            return AjaxResult.GetOK("添加成功！");
        }


        /// <summary>
        /// 进入设备归还页面
        /// </summary>
        /// <returns></returns>
        public IActionResult GoReturnPage(string id)
        {
            var log = _context.LendLog.Include(p=>p.Device).Single(p => p.Id == id);
            return View(log);
        }

        /// <summary>
        /// 归还设备
        /// </summary>
        /// <returns></returns>
        public AjaxResult ReturnDevice(LendLog obj)
        {
            var log = _context.LendLog.Single(p => p.Id == obj.Id);
            log.State = 2;
            log.ReturnDate = obj.ReturnDate;
            log.ReturnUser = obj.ReturnUser;
            _context.LendLog.Update(log);
            _context.SaveChanges();

            //更新设备状态
            var device = _context.Device.Single(p => p.Id == log.DeviceId);
            device.Status = DeviceState.STATE_NORMAL;
            _context.Device.Update(device);
            _context.SaveChanges();


            return AjaxResult.GetOK("归还成功！");
        }

    }
}